from app.libs.regexp import HOST_RE, SECOND_LEVEL_DOMAIN_RE, SUFFIX_RE
import tldextract


CHINA_SUFFIX = {'xn--zfr164b.cn': ['.xn--zfr164b.cn', '.\u653f\u52a1.cn'], 'xn--55qw42g': ['.xn--55qw42g', ]}
SPECIAL_SUFFIX = [u'中信', u'政务', u'公益', 'xn--55qw42g', 'xn--zfr164b.cn']


def domain_syntax_check(domain):
    """
    域名格式验证
    """
    def check_china_suffix(domain):
        try:
            domain = domain.encode('idna').decode()
        except UnicodeError:
            return None
        suffix = None
        for key, value in CHINA_SUFFIX.items():
            for v in value:
                if domain.endswith(v):
                    suffix = key
                    break
        return suffix
    china_suffix = check_china_suffix(domain)
    if china_suffix:
        domain = domain.encode('idna').decode()
        _split = domain.split(".")
        tld_suffix = china_suffix
        _index = -(len(tld_suffix.split(".")) + 1)
        tld_domain = _split[_index]
        tld_subdomain = ".".join(_split[:_index])
    else:
        tld = tldextract.extract(domain)
        if not tld.suffix:
            return None, None
        if not SECOND_LEVEL_DOMAIN_RE.match(tld.domain):
            # 中文域名处理
            try:
                # 若解码后字符串长度大于63将会异常
                tld_domain = tld.domain.encode('idna').decode()
            except Exception:
                return None, None
            # 中文域名解码后的验证
            if not SECOND_LEVEL_DOMAIN_RE.match(tld_domain):
                return None, None
        else:
            tld_domain = tld.domain
        if not SUFFIX_RE.match(tld.suffix):
            if tld.suffix not in SPECIAL_SUFFIX:
                return None, None
            tld_suffix = tld.suffix.encode('idna').decode()
        else:
            tld_suffix = tld.suffix
        try:
            tld_subdomain = tld.subdomain
        except Exception:
            return None, None
        if tld_subdomain and not all([HOST_RE.match(ts) for ts in tld_subdomain.split(".")]):
            return None, None
    root_domain = ".".join([tld_domain, tld_suffix])
    domain = ".".join([tld_subdomain, tld_domain, tld_suffix]) if tld_subdomain else root_domain
    return root_domain, domain
